package org.hackystat.ui.projectviewer.gwt.client.widgets;

import org.hackystat.ui.projectviewer.gwt.client.CSSStyles;
import org.hackystat.ui.projectviewer.gwt.client.common.MenuButton;

import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ClickListenerCollection;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SourcesClickEvents;
import com.google.gwt.user.client.ui.Widget;

/**
 * Provides menu panel for user actions.
 *
 * @author Pavel Senin.
 *
 */
public class UserActionWidget extends Composite implements ClickListener, SourcesClickEvents {

  /** {@literal} ACTION_REGISTER register action. */
  public static final String ACTION_REGISTER = "register";
  /** {@literal} ACTION_LOGIN login action. */
  public static final String ACTION_LOGIN = "login";

  /* The main outer pane */
  private final HorizontalPanel outer = new HorizontalPanel();

  private static final MenuButton registerButton = new MenuButton(ACTION_REGISTER);
  private static final MenuButton loginButton = new MenuButton(ACTION_LOGIN);

  private final ClickListenerCollection clickListeners = new ClickListenerCollection();

  private String action;

  /**
   * Does the menu construction.
   *
   */
  public UserActionWidget() {
    outer.setStyleName("projectMenuPanel");

    outer.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT);
    outer.add(loginButton);
    outer.add(registerButton);

    loginButton.setStyleName(CSSStyles.PROJECT_LIST_WIDGET_BUTTON);
    registerButton.setStyleName(CSSStyles.PROJECT_LIST_WIDGET_BUTTON);

    loginButton.addClickListener(this);
    registerButton.addClickListener(this);

    initWidget(outer);
  }

  /**
   * Menu click listener.
   *
   * @param sender The menu button clicked by user.
   */
  public void onClick(Widget sender) {

    if (sender instanceof MenuButton) {
      MenuButton mb = (MenuButton) sender;

      if (mb.equals(loginButton)) {
        this.action = ACTION_LOGIN;
        clickListeners.fireClick(this);
      }
      else if (mb.equals(registerButton)) {
        this.action = ACTION_REGISTER;
        clickListeners.fireClick(this);
      }
    }
  }

  /**
   * {@inheritDoc}
   */
  public void addClickListener(ClickListener listener) {
    this.clickListeners.add(listener);
  }

  /**
   * {@inheritDoc}
   */
  public void removeClickListener(ClickListener listener) {
    this.clickListeners.remove(listener);
  }

  /**
   * Report last fired action.
   *
   * @return The last fired action.
   */
  public String getAction() {
    return this.action;
  }

}
